import { join } from "path";
import process from 'node:process';
import { existsSync , writeFileSync } from 'fs';
/**
 * 获取根目录
 * @returns 根目录
 */
export function getRoot () {
  return process.cwd();
}
/**
 * 是否存在dist目录
 * @param {string} rootDir 根目录
 * @returns 布尔值，根目录下是否存在dist目录
 */
export function isExistDistDir (rootDir) {
  return existsSync(join(rootDir , './dist'));
}
/**
 * 获取dist目录
 * @param {string} rootDir 根目录
 * @returns dist目录
 */
export function getDistDir (rootDir) {
  return join(rootDir , './dist');
}

export function generateProxy (proxy = {}) {
  let content = '';
  const keys = Object.keys(proxy);
  keys.forEach(key => {
    let proxy_pass = proxy[key].target;
    const location = key[key.length - 1] === '/' ? key : key + '/';
    proxy_pass = proxy_pass[proxy_pass.length - 1] === '/' ? proxy_pass : proxy_pass + '/';
    content += `
      location ${location} {
        proxy_pass ${proxy_pass};
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $http_host;
        proxy_set_header X-Forwarded-Port $server_port;
        proxy_set_header X-Forwarded-Proto $scheme;
      }
    `
  });
  return content;
}

export function generateConfig (options) {
  const { port , address , proxy } = options;
  const proxyContent = generateProxy(proxy);
  const content = `
    server {
      listen ${port};
      location / {
        root ${address};
        index index.html;
        try_files $uri /index.html;
      }
      ${proxyContent}
    }
  `;
  return content;
}

export function createNginxConfigFile (rootDir , options) {
  const distDir = getDistDir(rootDir);
  writeFileSync(join(distDir , './nginx.conf') , generateConfig(options))
}